package com.xb.p19_broadcastdynamic;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button broadcast=findViewById(R.id.broadcast);
        broadcast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("test:","发送广播...");

                Intent intent=new Intent();
                intent.setAction("sendMsg");
                intent.putExtra("msg","这是一条广播消息");
                sendBroadcast(intent);
            }
        });


        final MyReceiver[] receiver = {null};
        final Button register=findViewById(R.id.register);
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //初始化
                Log.i("test:","注册...");
                receiver[0] =new MyReceiver();
                IntentFilter intentFilter=new IntentFilter();
                intentFilter.addAction("sendMsg");

                //注册接收器
                registerReceiver(receiver[0],intentFilter);
            }
        });


        final Button unregister=findViewById(R.id.unregister);
        unregister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消注册接收器
                Log.i("test:","取消注册...");
                unregisterReceiver(receiver[0]);
            }
        });


    }
}